package com.tools.web.http;

import com.tools.common.object.C;
import com.tools.common.object.Note;
import org.apache.poi.ss.formula.functions.T;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

interface HttpDataFrom {

    @Note("自定义数据 Map 集合的名称")
    String OWN_DATA_MAP = "ownDataMap";

    String getData(HttpServletRequest request, String name);

    <T> T getData(HttpServletRequest request, String name, C<T> valueType);

    void setData(HttpServletRequest request, HttpServletResponse response, String name, Object value);

    default boolean ownDataMapIsEmpty(HttpServletRequest request) {
        Map<String, Object> ownDataMap = this.getOwnDataMap(request);
        return ownDataMap == null || ownDataMap.isEmpty();
    }

    default Map<String, Object> getOwnDataMap(HttpServletRequest request) {
        return (Map<String, Object>) request.getAttribute(OWN_DATA_MAP);
    }

    default Map<String, Object> getOrSetOwnDataMap(HttpServletRequest request) {
        Map<String, Object> ownDataMap = this.getOwnDataMap(request);
        if (ownDataMap == null) {
            ownDataMap = new HashMap<>();
            request.setAttribute(OWN_DATA_MAP, ownDataMap);
        }
        return ownDataMap;
    }
}
